import json

from django import http
from django.views.generic.base import View
from fdfs_client.client import Fdfs_client

from aijia_house.utils.login import LoginRequiredJSONMixin
from apps.address.models import Area
from apps.house.models import House, Facility, HouseImage
from aijia_house import settings

# 发布房源信息
class HouseRelease(LoginRequiredJSONMixin, View):
    def post(self, request):
        """
        发布房源
            1. 接收参数/参数校验
            2. 将参数的数据保存到新创建house模型
            3. 保存house模型到数据库
            返回给前端json数据
            {
                "title":"",
                "price":"",
                "area_id":"1",
                "address":"",
                "room_count":"",
                "acreage":"",
                "unit":"",
                "capacity":"",
                "beds":"",
                "deposit":"",
                "min_days":"",
                "max_days":"",
                "facility":["7","8"]
            }
        """

        # 1. 取到参数
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        price = json_dict.get('price')
        address = json_dict.get('address')
        area_id = json_dict.get('area_id')
        room_count = json_dict.get('room_count')
        acreage = json_dict.get('acreage')
        unit = json_dict.get('unit')
        capacity = json_dict.get('capacity')
        beds = json_dict.get('beds')
        deposit = json_dict.get('deposit')
        min_days = json_dict.get('min_days')
        max_days = json_dict.get('max_days')

        # 1.1 判断是否都有值
        if not all(
                [title, price, address, area_id, room_count, acreage, unit, capacity, beds, deposit, min_days,
                 max_days]):
            return http.JsonResponse({'errno': 4004, 'errmsg': "参数有误"})
        # 1.2 校验参数格式是否正确
        try:
            price = int(float(price) * 100)
            deposit = int(float(deposit) * 100)
        except Exception as e:

            return http.JsonResponse({'errno': 4103, 'errmsg': "参数有误"})
        try:
            area = Area.objects.get(id=area_id)
        except Exception as e:

            return http.JsonResponse({'errno': 4103, 'errmsg': "参数有误"})

        try:
            house = House.objects.create(user=request.user, area=area, title=title, price=price, address=address,
                                         room_count=room_count, acreage=acreage, unit=unit, capacity=capacity,
                                         beds=beds, deposit=deposit, min_days=min_days, max_days=max_days)
        except Exception as e:

            return http.JsonResponse({'errno': 4001, 'errmsg': "数据库问题"})

        # 获取到当前房屋的设施列表数组
        facilities = json_dict.get("facility")
        facilities = Facility.objects.filter(id__in=facilities)
        house.facilities.add(*facilities)

        # 3.保存house模型到数据库

        try:
            house.save()
        except Exception as e:

            return http.JsonResponse({'errno': 4001, 'errmsg': "数据保存错误"})
        return http.JsonResponse({'errno': 0, 'errmsg': "Ok", 'data': {"house_id": house.id}})

# 上传房源图片
class HouseImageUpload(View):
    '''房屋图片'''

    def post(self, request, house_id):
        '''房屋图片上传
            1. 取到上传的图片
            2. 进行七牛云上传
            3. 将上传返回的图片地址存储
            4. 进行返回
        '''
        # 1. 取到上传的图片
        content = request.FILES.get('house_image')
        if content is None:
            return http.JsonResponse({'errno': 4103, 'errmsg': "参数错误"})

        # 2. 查询房屋是否存在
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return http.JsonResponse({'errno': 4002, 'errmsg': "房屋不存在"})

        # 3. 上传到Fdfs

        try:
            client = Fdfs_client(settings.dev.FDFS_CLIENT_CONF)
            result = client.upload_by_buffer(content.read())
        except Exception as e:

            return http.JsonResponse({'errno': 4301, 'errmsg': "上传图片错误"})

        # 4. 初始化房屋的图片模型
        # 上传成功：返回file_id,拼接图片访问URL
        file_id = result.get('Remote file_id')
        url = settings.dev.FDFS_URL + file_id
        try:
            house_image = HouseImage.objects.create(house=house, url=url)
        except Exception as e:

            return http.JsonResponse({'errno': 4001, 'errmsg': "保存数据失败"})

        # 判断是否有首页图片
        if not house.index_image_url:
            # 保存图片地址
            house.index_image_url = url
            house.save()

        return http.JsonResponse({'errno': 0, 'errmsg': "OK", 'data': {"url": url}})